<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html>
<html>
<head>
<title>运输追踪管理</title>
<jsp:include page="../inc.jsp"></jsp:include>
<c:if
	test="${fn:contains(sessionInfo.resourceList, '/transportController/delete')}">
	<script type="text/javascript">
		$.canDelete = true;
	</script>
</c:if>

<script type="text/javascript">
	var dataGrid;
	var detaildata;
	$(function(){
		dataGrid = $('#dataGrid').datagrid({
							url : '${pageContext.request.contextPath}/transportController/dataGrid',
							fit : true,
							border : false,
							pagination : true,
							idField : 'id',
							fitColumns : false,
							pageSize : 30,
							pageList : [ 10, 20, 30, 40, 50 ],
							sortName : 'code',
							sortOrder : 'asc',
							checkOnSelect : true,
							selectOnCheck : true,
							nowrap : false,
							view : detailview,
							frozenColumns : [ [ {
								field : 'id',
								title : '序号',
								width : 10,
								checkbox : true
							},{
                                field : 'code',
                                title : '订单号',
                                width : 60,
                                sortable : true,
                            }] ],
							columns : [ [{
								field : 'type',
								title : '订单类型',
								width : 60,
								formatter : function(value, row, index) {
									switch (value) {
									case 'LAND':
										return '陆运';
									case 'AIR':
										return '空运';
									case 'SEA':
										return '海运';
									}
								}
							},{
								field : 'status',
								title : '送货单状态',
								width : 80,
								sortable : true,
								formatter : function(value, row, index) {
									switch (value) {
									case 'NEW':
										return '新建';
									case 'SHIP':
										return '发货';
									case 'ARRIVE':
										return '到货';
									}
								}
							},{
                                field : 'createTime',
                                title : '订单创建时间',
                                width : 80
                            },{
                                field : 'ownerId',
                                title : '货主id',
                                width : 40,
                                hidden : true
                            },{
									field : 'ownerName',
									title : '货主',
									width : 60,
								}, {
									field : 'factoryId',
									title : '发货仓库Id',
									width : 60,
									hidden : true
								},{
									field : 'factoryName',
									title : '发货仓库',
									width : 60,
								},{
                                field : 'carrierId',
                                title : '承运商Id',
                                width : 100,
                                hidden : true
                            },{
									field : 'carrierName',
									title : '承运商',
									width : 60,
								},{
									field : 'sendTime',
									title : '发货时间',
									width : 80,
								},{
                                field : 'sendNo',
                                title : '发货标识',
                                width : 80,
                            	},{
                                field : 'send',
                                title : '是否发送邮件',
                                width : 60,
                                formatter : function(value, row, index) {
                                    if(value==true){
                                        return '<span>已发邮件</span>';
                                    }else if(value==false){
                                        return '<span>未发邮件</span>';
                                    }
                                }
                            },{
									field : 'sendRemark',
									title : '发货备注',
									width : 100,
								},{
									field : 'receiveTime',
									title : '到货时间',
									width : 80,
								},{
                                field : 'receiveType',
                                title : '到货方式',
                                width : 80,
                            },{
									field : 'receiveRemark',
									title : '到货备注',
									width : 100
								},{
										field : 'action',
										title : '操作',
										width : 40,
										formatter : function(value, row, index) {
											var str = '';
											if ($.canEdit) {
												str += $
														.formatString(
																'<img onclick="editFun(\'{0}\');" src="{1}" title="编辑订单"/>',
																row.id,
																'${pageContext.request.contextPath}/style/images/extjs_icons/pencil.png');
											}
											str += '&nbsp;';
											if ($.canDelete) {
												str += $
														.formatString(
																'<img onclick="deleteFun(\'{0}\');" src="{1}" title="删除"/>',
																row.id,
																'${pageContext.request.contextPath}/style/images/extjs_icons/cancel.png');
											}
											return str;
										}
									} ] ],
							toolbar : '#toolbar',
							onDblClickRow : function(index, row) {
								window.open("${pageContext.request.contextPath}/business/traceDetail.jsp?id="+ row.id);
								parent.$.messager.progress('close');
							},
							onLoadSuccess : function() {
								$('#searchForm table').show();
								parent.$.messager.progress('close');

								$(this).datagrid('tooltip');
							},
							onRowContextMenu : function(e, rowIndex, rowData) {
								e.preventDefault();
								$(this).datagrid('unselectAll').datagrid('uncheckAll');
								var row = $(this).datagrid('selectRow',rowIndex);
								if (rowData != null) {
									$('#menu').menu('show', {
										left : e.pageX,
										top : e.pageY
									});
								}
							},
							detailFormatter : function(index, row) {
								return '<div style="padding:2px"><table id="ddv-' + index + '"></table></div>';
							},
							onExpandRow : function(index, row) {
								detaildata = $('#ddv-' + index).datagrid({
													url : '${pageContext.request.contextPath}/transportDetailController/transportDetail?id='+ row.id,
													fitColumns : false,
													idField : 'id',
													sortName : 'productId',
													sortOrder : 'asc',
													remoteSort:false,
													/* singleSelect : true, */
													checkOnSelect : true,
													selectOnCheck : true,
													height : 'auto',
													frozenColumns : [ [{
																			field : 'id',
																			title : '明细序号',
																			width : 20,
																			checkbox : true
																		},{
																			field : 'retransportId',
																			title : 'ID',
																			width : 50,
																			hidden : true
																		}] ],
																		columns : [ [{
																			field : 'productId',
																			title : '产品Id',
																			width : 80,
																			hidden : true
																		},{
                                                                            field : 'productCode',
                                                                            title : '产品编码',
                                                                            width : 80
                                                                        },{
																			field : 'productName',
																			title : '产品名称',
																			width : 80
																		},{
																		field : 'productDetail',
																		title : '产品描述',
																		width : 100,
																	},{
																		field : 'qty',
																		title : '订货数',
																		width : 80,
																	},{
																		field : 'weight',
																		title : '订货重量',
																		width : 80,
																	},{
																		field : 'volume',
																		title : '订货体积',
																		width : 80,
																	}] ],
													onResize : function() {
														$('#dataGrid').datagrid('fixDetailRowHeight',index);
													},
													onLoadSuccess : function() {
														setTimeout(
																function() {
																	$('#dataGrid').datagrid('fixDetailRowHeight',index);
																}, 0);
													},
													//second start
								                    });	
													//second end
								$('#dataGrid').datagrid('fixDetailRowHeight',index);
							}

						});
	});
	
	function deleteDetailFun(id) {
		if (id == undefined) {//点击右键菜单才会触发这个
			var rows = dataGrid.datagrid('getSelections');
			id = rows[0].id;
		} else {//点击操作里面的删除图标会触发这个
			dataGrid.datagrid('unselectAll').datagrid('uncheckAll');
			detaildata.datagrid('unselectAll').datagrid('uncheckAll');
			detaildata.datagrid('selectRecord',id); //selectRecord 通过ID值参数选择一行。
		}
		var f = false;
		var status =detaildata.datagrid('getSelections')[0].status;
		if(detaildata.datagrid('getSelections')[0].type == 'CUSTOMER'){ //客户订单先预约再发货，所以订单状态为新建和预约的都可以执行删除
			if(status=='NEW' || status=='BOOKING'){
				f=true;
			} 
		}else if(detaildata.datagrid('getSelections')[0].type == 'DB'){ //调拨订单先发货再预约，所以订单状态为新建的才可以执行删除
			if(status=='NEW'){
				f=true;
			} 
		}
		if(f){
		parent.$.messager.confirm(
						'询问',
						'您是否要删除当前产品？',
						function(b) {
							if (b) {
								var currentUserId = '${sessionInfo.id}';/*当前登录用户的ID*/
								if (currentUserId != id) {
									parent.$.messager.progress({
										title : '提示',
										text : '数据处理中，请稍后....'
									});
									$.post('${pageContext.request.contextPath}/retransportDetailController/delete',{
														id : id
													},
													function(result) {
														if (result.success) {
															parent.$.messager.alert('提示',result.msg,'info');
															dataGrid.datagrid('reload');
															dataGrid.datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
														}
														parent.$.messager.progress('close');
													}, 'JSON');
								} else {
									parent.$.messager.show({
										title : '提示',
										msg : '不可以删除自己！'
									});
								}
							}
						});
		}else {
			parent.$.messager.show({
				title : '提示',
				timeout:0,
				width:250,
				height:150,
				style:{
					right:'',
					top:250,
					bottom:''
				},
				msg : '已发货的订单明细不能被删除！'
			});
		}
	}
    function deleteFun(id) {
        var f=true;
        if (id == undefined) {   //点击右键菜单才会触发这个
            var rows = dataGrid.datagrid('getSelections');
            id = rows[0].id;
        } else {//点击操作里面的删除图标会触发这个
            dataGrid.datagrid('unselectAll').datagrid('uncheckAll');
            dataGrid.datagrid('selectRecord',id); //selectRecord 通过ID值参数选择一行。
        }
            parent.$.messager.confirm('询问','您是否要删除当前订单？',function(b) {
                if (b) {
                    parent.$.messager.progress({
                        title : '提示',
                        text : '数据处理中，请稍后....'
                    });
                    $.post('${pageContext.request.contextPath}/transportController/delete',{
                            id : id
                        },
                        function(result) {
                            if (result.success) {
                                parent.$.messager.alert('提示',result.msg,'info');
                                dataGrid.datagrid('reload');
                                dataGrid.datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
                            }else{
                                parent.$.messager.progress('close');
							}
                        }, 'JSON');
                }
            });
    }


    function batchDeleteFun() {

        var rows = dataGrid.datagrid('getChecked');
        var ids = [];
        var f = true;
        if (rows.length > 0) {
            if(f){
                parent.$.messager.confirm(
                    '确认','您是否要删除当前选中的订单？',
                    function(r) {
                        if (r) {
                            parent.$.messager.progress({
                                title : '提示',
                                text : '数据处理中，请稍后....'
                            });
                            var currentUserId = '${sessionInfo.id}';/*当前登录用户的ID*/
                            var flag = false;
                            for (var i = 0; i < rows.length; i++) {
                                if (currentUserId != rows[i].id) {
                                    ids.push(rows[i].id);
                                } else {
                                    flag = true;
                                }
                            }
                            $.getJSON('${pageContext.request.contextPath}/transportController/batchDelete',{
                                    ids : ids.join(',')
                                },
                                function(result) {
                                    if (result.success) {
                                        dataGrid.datagrid('load');
                                        dataGrid.datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
                                    }else {
                                        parent.$.messager.progress('close');
                                        parent.$.messager.alert('提示',result.msg,'info');
                                    }

                                });
                        }
                    });
            }else{
                parent.$.messager.show({
                    title : '提示',
                    timeout:0,
                    width:250,
                    height:150,
                    style:{
                        right:'',
                        top:250,
                        bottom:''
                    },
                    msg : '删除失败，勾选数据中存在已发货的订单！'
                });
            }
        } else {
            parent.$.messager.show({
                title : '提示',
                timeout:0,
                width:250,
                height:150,
                style:{
                    right:'',
                    top:250,
                    bottom:''
                },
                msg : '请勾选要删除的记录！'
            });
        }
    }

	
	function editFun(id) {
		if (id == undefined) {
			var rows = dataGrid.datagrid('getSelections');
			id = rows[0].id;
		} else {
			dataGrid.datagrid('unselectAll').datagrid('uncheckAll');
			dataGrid.datagrid('selectRecord',id); //selectRecord 通过ID值参数选择一行。
		}
		/* var f = false;
		var status = dataGrid.datagrid('getSelections')[0].status;
		if(dataGrid.datagrid('getSelections')[0].type=='CUSTOMER'){
			if(status=='NEW' || status=='BOOKING'){
				f=true;
			} 
		}else if(dataGrid.datagrid('getSelections')[0].type=='DB'){
			if(status=='NEW'){
				f=true;
			} 
		}
		if(f){ */
		parent.$.modalDialog({
					title : '编辑订单',
					width : 900,
					height : 510,
					href : '${pageContext.request.contextPath}/retransportController/retransportEdit?id='+ id,
					buttons : [ {
						text : '提交',
						handler : function() {
							parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
							var f = parent.$.modalDialog.handler.find('#form');
							f.submit();
						}
					} ]
				});
		/*  }else{
				parent.$.messager.show({
					title : '提示',
					msg : '不能编辑已发货的订单！'
				}); 
			} */
	}
	
	function editDetailFun(id) {
		if (id == undefined) {
			var rows = dataGrid.datagrid('getSelections');
			id = rows[0].id;
		} else {
			dataGrid.datagrid('unselectAll').datagrid('uncheckAll');
			detaildata.datagrid('unselectAll').datagrid('uncheckAll');
			detaildata.datagrid('selectRecord',id); //selectRecord 通过ID值参数选择一行。
		}
		/* var f = false;
	    var s = detaildata.datagrid('getSelections')[0].status;
		if(detaildata.datagrid('getSelections')[0].type=='CUSTOMER'){
			if(s=='NEW' || s=='BOOKING'){
				f=true;
			} 
		}else if(detaildata.datagrid('getSelections')[0].type=='DB'){
			if(s=='NEW'){
				f=true;
			} 
		}
		if(f){ */ 
		parent.$.modalDialog({
					title : '编辑明细',
					width : 500,
					height : 300,
					href : '${pageContext.request.contextPath}/retransportDetailController/retransportDetailEdit?id='+ id,
					buttons : [ {
						text : '提交',
						handler : function() {
							parent.$.modalDialog.openner_dataGrid = dataGrid;//因为添加成功之后，需要刷新这个dataGrid，所以先预定义好
							var f = parent.$.modalDialog.handler.find('#form');
							f.submit();
						}
					} ]
				});
		/* }else{
			parent.$.messager.show({
				title : '提示',
				msg : '不能编辑已发货的订单！'
			});
		}  */
	}
	function uploadPhotoFun() {
		/* var id;
		if (id == undefined) {
			var rows = dataGrid.datagrid('getSelections');
			id = rows[0].id;
		} else {
			dataGrid.datagrid('unselectAll').datagrid('uncheckAll');
		} */
		window.open("${pageContext.request.contextPath}/retransportController/uploadPhoto");
	}

	function importExcel() {
		var p = parent.$
				.modalDialog({
					title : '导入',
					width : 500,
					height : 300,
					href : '${pageContext.request.contextPath}/productController/importExcel',
					buttons : [ {
						text : '导入',
						handler : function() {
							var f = p.find('form');
							f.form('submit',{
												url : '${pageContext.request.contextPath}/transportController/transportImport',
												success : function(d) {
													var json = $.parseJSON(d);
													if (json.success) {
														dataGrid.datagrid('load');
														dataGrid.datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
														p.dialog('close');
													}

													parent.$.messager.show({
														title : '提示!',
														timeout:0,
														width:250,
														height:150,
														style:{
															right:'',
															top:250,
															bottom:''
														},
														msg : json.msg
													});
												}
											});
						}
					} ]
				});
	}

	function searchFun(e){
		dataGrid.datagrid('load', $.serializeObject($('#searchForm')));
		dataGrid.datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
	}
	function cleanFun() {
		$('#searchForm input').val('');
        $('#searchForm select').val('');
		dataGrid.datagrid('load', {});
	}
	function downloadFun() {
		$('#win').window({
			title:'单击下載',
			collapsible:false,
			minimizable : false,
			left : 0,
			top :87,
		    width:160,
		    height:200,
		    modal:true
		});
	}
	
	//订单导出
	 function exportExcel() {
	 var deliverys = $('#deliverys').val().trim();
	 var url='${pageContext.request.contextPath}/retransportController/retransportExport';
	
	 if(deliverys.length<=0){
			$.messager.show({
				title:'提示',
				timeout:0,
				width:250,
				height:150,
				style:{
					right:'',
					top:250,
					bottom:''
				},
				msg:'导出必须输入送货单号',
			});
	 }else{  
		// var d ;
			 if (deliverys != null) {
				  /* $.ajax({
					   type: "POST",
					   url: url,
					   datatype : "text",
					   data: "deliverys="+ deliverys,
					   success : function(data,datatype) {
						//   window.location.href = data;
						   d=data,
						   alert(d)
						  // d=d.substring(1, d.length-1),
						 //  window.location.href = d
					   },
					   error : function() {
					   console.log("请求失败");
					   } 
				 });  */
				 
				//  window.open("../transport20170110131741.xls")
		    	url = url + "?deliverys="+ deliverys;
			 }
			 window.location.href = url;
	 } 
	}
	 /* function exportExcel() {
	 var rows = dataGrid.datagrid('getChecked');
		var ids="";
		var f=true;
		if (rows.length > 0) {
			parent.$.messager.confirm(
					'确认','您是否要导出当前选中的订单数据？',
					function(r) {
						if (r) {
							for (var i = 0; i < rows.length; i++) {
								ids+=rows[i].id+",";
								
							}
							ids = ids.substring(0, ids.length-1);
							window.location.href = "${pageContext.request.contextPath}/retransportController/retransportExport?ids="+ids;
						}
					});
		} else {
			parent.$.messager.show({
				title : '提示',
				msg : '请勾选要导出的记录！'
			});
		}
	} */
	 
	 function showPhotoFun(id) { 
		var rows = dataGrid.datagrid('getSelections');
		id = rows[0].id; 
		window.open("${pageContext.request.contextPath}/business/pictureDetail.jsp?id="+id);
			parent.$.messager.progress('close');
	 }
	 function levelImport() {
			var p = parent.$
					.modalDialog({
						title : '导入',
						width : 500,
						height : 300,
						href : '${pageContext.request.contextPath}/productController/importExcel',
						buttons : [ {
							text : '导入',
							handler : function() {
								var f = p.find('form');
								f.form('submit',{
													url : '${pageContext.request.contextPath}/retransportController/levelImport',
													success : function(d) {
														var json = $.parseJSON(d);
														if (json.success) {
															dataGrid.datagrid('load');
															dataGrid.datagrid('uncheckAll').datagrid('unselectAll').datagrid('clearSelections');
															p.dialog('close');
														}

														parent.$.messager.show({
															title : '提示',
															timeout:0,
															width:250,
															height:150,
															style:{
																right:'',
																top:250,
																bottom:''
															},
															msg : json.msg
														});
													}
												});
							}
						} ]
					});
		}

	 
	//针对数字列自定义排序
		function sort_int(a,b){  
		    if(a.length > b.length) return 1;
		        else if(a.length < b.length) return -1;
		        else if(a > b) return 1;
		        else return -1;
		}
</script>
</head>
<body>
	<div class="easyui-layout" data-options="fit : true,border : false">
		<div data-options="region:'north',title:'查询条件',border:false"
			style="height: 60px; overflow: hidden;">
			<form id="searchForm">
				<table class="table table-hover table-condensed"
					style="display: none;">
					<tr>
						<th>订单号</th>
						<td><input name="codes" id="deliverys" placeholder="多条查询用,号分割" class="span2" onkeydown="if(event.keyCode==13 || event.which==13){searchFun(event);}"/></td>
						<th>订单类型</th>
						<td>
							<select name="type" style="width: 90px;height: 30px" onkeydown="if(event.keyCode==13  || event.which==13 ){searchFun(event);}">
								<option value="">-请选择-</option>
								<option value="LAND">陆运</option>
								<option value="ATR">空运</option>
								<option value="SEA">海运</option>
							</select>
						</td>
						<th>订单状态</th>
						<td>
							<select name="status" style="width: 90px;height: 30px" onkeydown="if(event.keyCode==13  || event.which==13 ){searchFun(event);}">
								<option value="">-请选择-</option>
								<option value="NEW">新建</option>
								<option value="SHIP">发货</option>
								<option value="ARRIVE">到货</option>
							</select>
						</td>
						<th>创建时间</th>
						<td><input name="createTimeStart" placeholder="点击选择日期" class="span2" onkeydown="if(event.keyCode==13 || event.which==13){searchFun(event);}" onclick="WdatePicker({readOnly:true,dateFmt:'yyyy-MM-dd 00:00:00'})" readonly="readonly" />至<input class="span2" name="createTimeEnd" placeholder="点击选择日期" onkeydown="if(event.keyCode==13 || event.which==13){searchFun(event);}" onclick="WdatePicker({readOnly:true,dateFmt:'yyyy-MM-dd  00:00:00'})" readonly="readonly"></td>
					</tr>

				</table>
			</form>
		</div>
		<div data-options="region:'center',border:false">
			<table id="dataGrid"></table>
		</div>
	</div>
	<div id="toolbar" style="display: none;">
	<a onclick="downloadFun();" href="javascript:void(0);" class="easyui-linkbutton" data-options="plain:true,iconCls:'link_go'">导入模板下载</a>
		<c:if
			test="${fn:contains(sessionInfo.resourceList, '/retransportController/addPage')}">
			<a onclick="addFun();" href="javascript:void(0);"
				class="easyui-linkbutton"
				data-options="plain:true,iconCls:'pencil_add'">添加</a>
		</c:if>
		<c:if
			test="${fn:contains(sessionInfo.resourceList, '/transportController/transportImport')}">
			<a onclick="importExcel();" href="javascript:void(0);"
				class="easyui-linkbutton" data-options="plain:true,iconCls:'tux'">导入</a>
		</c:if>
		<c:if
			test="${fn:contains(sessionInfo.resourceList, '/retransportController/retransportExport')}">
			<a onclick="exportExcel();" href="javascript:void(0);"
				class="easyui-linkbutton" data-options="plain:true,iconCls:'tux'">导出</a>
		</c:if>
		<%--<c:if
			test="${fn:contains(sessionInfo.resourceList, '/retransportController/batchDelete')}">
			<a onclick="batchDeleteFun();" href="javascript:void(0);"
				class="easyui-linkbutton" data-options="plain:true,iconCls:'delete'">批量删除</a>
		</c:if>--%>
    <%--/adminDelete--%>
        <c:choose>
            <c:when test="${fn:contains(sessionInfo.resourceList, '/transportController/batchDelete') and fn:contains(sessionInfo.resourceList, '/adminDelete')}">
                <a onclick="adminBatchDeleteFun();" href="javascript:void(0);"
                   class="easyui-linkbutton" data-options="plain:true,iconCls:'delete'">批量删除</a>
            </c:when>
            <c:when test="${fn:contains(sessionInfo.resourceList, '/transportController/batchDelete')}">
                <a onclick="batchDeleteFun();" href="javascript:void(0);"
                   class="easyui-linkbutton" data-options="plain:true,iconCls:'delete'">批量删除</a>
            </c:when>
        </c:choose>



		<a href="javascript:void(0);" class="easyui-linkbutton"
			data-options="iconCls:'brick_add',plain:true" onclick="searchFun(event);">查询</a>
			<a href="javascript:void(0);" class="easyui-linkbutton"
			data-options="iconCls:'brick_delete',plain:true"
			onclick="cleanFun();">重新查询</a>
        <c:choose>
            <c:when test="${fn:contains(sessionInfo.resourceList, '/retransportController/delete') and fn:contains(sessionInfo.resourceList, '/adminDelete')}">
                <div onclick="adminDeleteFun();" data-options="iconCls:'pencil_delete'">删除订单</div>
            </c:when>
            <c:when test="${fn:contains(sessionInfo.resourceList, '/retransportController/delete')}">
                <div onclick="deleteFun();" data-options="iconCls:'pencil_delete'">删除订单</div>
            </c:when>
        </c:choose>
	</div>
	<div id="win">
        <font size="3" style="font-family: 华文仿宋">---单击下载模板---</font><br><br>
        <a href="${pageContext.request.contextPath}/template/createOrder.xls" >●创建订单模板</a><br>
		<a href="${pageContext.request.contextPath}/template/shipOrder.xls" >●发货模板</a><br>
		<a href="${pageContext.request.contextPath}/template/arriveOrder.xls" >●到货模板</a><br>
	</div>
</body>
</html>